package com.yaolaizaixian.merchant.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.Customer;
import com.yaolaizaixian.merchant.bean.MemberInfo;
import com.yaolaizaixian.merchant.bean.MemberInfoModel;
import com.yaolaizaixian.merchant.order.QueryResultActivity;
import com.yaolaizaixian.merchant.order.SearchActivity;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/3/8.
 */
public class SaoMaActivity extends BaseActivity {


    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.fl_my_container)
    FrameLayout flMyContainer;
    @BindView(R.id.activity_second)
    AutoLinearLayout activitySecond;
    private String type;
    private String code;
    private String sign;

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {
                        MemberInfoModel memberInfoModel = GsonUtil.jsonToBean(result, MemberInfoModel.class);
                        MemberInfo memberInfo = memberInfoModel.getData();
                        Customer customer = memberInfo.getCustomer();

                        if (null != customer) {

                            if (!TextUtils.isEmpty(type) && type.equals("1")) {
                                Intent intent = new Intent(SaoMaActivity.this, QueryResultActivity.class);
                                intent.putExtra("phone", code);
                                startActivity(intent);
                                finish();
                            }

                        } else {

                            Toasty.error(getApplicationContext(), "会员不存在", Toast.LENGTH_SHORT).show();
                            finish();

                        }

                    } else {

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode))
                        {
                            showConflictDialog(SaoMaActivity.this,"账号被停用");

                        }else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)){

                            showConflictDialog(SaoMaActivity.this,"您的账号在其它设备登录");

                        }else
                        {
                            Toasty.error(getApplicationContext(), baseModel.getErrorMsg(), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        return;

                    }
                    break;

            }
        }
    };

    @Override
    public void initView() {

        setContentView(R.layout.activity_saoma);

    }

    @Override
    public void initData() {

        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        sign = intent.getStringExtra("sign");
        tvTitleText.setText("收单页");
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();

    }


    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {


            code = result;

            if ("1".equals(sign)) {

                getData(code);

            } else {

                Intent intent = new Intent(SaoMaActivity.this, SearchActivity.class);
                intent.putExtra("phone", result);
                startActivity(intent);
                finish();
            }


        }

        @Override
        public void onAnalyzeFailed() {

            Toasty.error(getApplicationContext(), "扫码失败", Toast.LENGTH_SHORT).show();

            finish();

            return;
        }
    };

    //获取会员信息信息接口
    private void getData(String phone) {

        String shopsysno = SharedPreferencesUtil.getString(getApplicationContext(), "shopsysno", "");
        //店铺id
        final String url = BaseInfo.URL + "customerInfo/info.do";
        HashMap<String, String> sortedParams = new HashMap<String, String>();
        // sysNo 值  3des加密
        sortedParams.put("cardNumber", phone);
        sortedParams.put("shopStoreSysno", shopsysno);
        //类型，1：手机号，2：卡号
//        sortedParams.put("cardType", "2");
//        sortedParams.put("equityRuleType", "2");
        //判断是抵扣 还是抵用
        if (!TextUtils.isEmpty(type) && type.equals("1")) {
            //权益类型：1抵扣 2抵用
            sortedParams.put("equityRuleType", "2");
        } else {
            //1抵扣 2抵用
            sortedParams.put("equityRuleType", "1");
        }

        Log.e(TAG, "cardNumber" + phone);
        Log.e(TAG, "shopStoreSysno" + shopsysno);

        OkHttpUtils
                .post()
                .url(url)
                .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                .build()
                .execute(new MyStringCallback());

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.ll_back)
    public void onClick() {

        finish();
    }


    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            Toasty.error(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();

            finish();

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }
}
